<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>地图定位</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="less/public.css" type="text/css">
    <script src="./jquery.js" type="text/javascript"></script>
    <script src="http://api.map.baidu.com/api?v=2.0&ak=YG2iv0eCzo1z6YTsau5pgd24"></script>
    <script type="text/javascript" src="./LuShu_min.js"></script>
    <style type="text/css">
        body,
        html {
            width: 100%;
            height: 100%;
            margin: 0;
            font-family: "微软雅黑";
        }

        #map_canvas {
            width: 100%;
            height: 100%;
        }

        #result {
            width: 100%
        }
    </style>
</head>

<body>
<div id="map_canvas"></div>
<div id="result"></div>
</body>
<script>
    var allPoint = [];
    var mapPoint = [];
    var carNum = [];
    var map = new BMap.Map('map_canvas');
    map.enableScrollWheelZoom();
    map.centerAndZoom("南京");
    $(function () {
        $.ajax({
            url: 'http://api.jshrdtz.com/api/register/isLogin',
            type: 'get',
            xhrFields: {
                withCredentials: true
            },
            success: function (res) {
                console.log(res);
                if (res === true) {
                    connectWebSocket()
                } else {
                    alert("您还未登录，请先登录！！");
                    location.href = "http://m.jshrdtz.com"
                }
            }
        })
    });

    function connectWebSocket() {

        //判断当前浏览器是否支持WebSocket
        if ('WebSocket' in window) {
            websocket = new WebSocket("ws://api.jshrdtz.com/websocket");
        } else {
            alert('Not support websocket')
        }


        //连接发生错误的回调方法
        websocket.onerror = function () {
            setMessageInnerHTML("error");
        };

        //连接成功建立的回调方法
        websocket.onopen = function (event) {
            setMessageInnerHTML('{}');
        }

        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            setMessageInnerHTML(event.data);
        }

        //连接关闭的回调方法
        websocket.onclose = function () {
            setMessageInnerHTML("Loc MSG:" + "关闭连接");
        }

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            websocket.close();
        }
    }


    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        var curdata = JSON.parse(innerHTML);
        if ($.isEmptyObject(curdata)) {
            return;
        }
        if ((curdata.code && curdata.code !== 0)) {
            alert(curdata.message);
            return;
        }
        if (curdata.result.length === 0) {
            return;
        }
        console.log(curdata.result)
        alert(123)
        $.each(curdata.result, function (index, obj) {
            if (allPoint.length === 0) {
                for (let i = 0; i < curdata.result.length; i++) {
                    allPoint.push([]);
                    mapPoint.push([]);
                }
            }
            allPoint[index].push({"lat": obj.lat, "lng": obj.lng, "carNo": obj.carNo});
            mapPoint[index].push(new BMap.Point(obj.lng, obj.lat));
            carNum[index] = obj.carNo;

        });
        setMap(allPoint)

        setLushu(mapPoint)

    }

    //关闭连接
    function closeWebSocket() {
        websocket.close();
    }

    //发送消息
    function send() {
        var message = document.getElementById('text').value;
        var toUser = document.getElementById('toUser').value;
        var socketMsg = {msg: message, toUser: toUser};
        if (toUser == '') {
            //群聊.
            socketMsg.type = 0;
        } else {
            //单聊.
            socketMsg.type = 1;
        }

        websocket.send(JSON.stringify(socketMsg));
        // websocket.send(message);
    }


    var instanceArr = []

    function setMap(points) {
        $.each(points, function (index, obj) {
            console.log(obj)
            var curpoint = new BMap.Point(obj[0].lng, obj[0].lat);
            var curmarker = new BMap.Marker(curpoint, {
                icon: new BMap.Icon('http://developer.baidu.com/map/jsdemo/img/car.png', new BMap.Size(52, 26), {anchor: new BMap.Size(27, 13)})
            });

            var label = new BMap.Label(obj[0].carNo, {offset: new BMap.Size(0, -30)});
            label.setStyle({
                border: "1px solid rgb(204, 204, 204)",
                color: "rgb(0, 0, 0)",
                borderRadius: "10px",
                padding: "5px",
                background: "rgb(255, 255, 255)",
            });
            curmarker.setLabel(label);

            map.addOverlay(curmarker);
            curmarker.enableMassClear(); //设置后可以隐藏改点的覆盖物
            curmarker.hide();
//            instanceArr[index] = (lushuInstance(obj));

        });


    }

    function setLushu(points) {
        $.each(points, function (index, obj) {
            if (instanceArr.length < 6) {
//                instanceArr.push(lushuInstance(obj))
                instanceArr[index] = lushuInstance(obj, carNum[index]);

            }

        });

        console.log(instanceArr)
        map.clearOverlays();

        for (var i = 0; i < 5; i++) {

            startLushu(i);
        }
    }


    //                路书
    BMapLib.LuShu.prototype._move = function (initPos, targetPos, effect) {
        var pointsArr = [initPos, targetPos];  //点数组
        var me = this,
            //当前的帧数
            currentCount = 0,
            //步长，米/秒
            timer = 10,
            step = this._opts.speed / (1000 / timer),
            //初始坐标
            init_pos = this._projection.lngLatToPoint(initPos),
            //获取结束点的(x,y)坐标
            target_pos = this._projection.lngLatToPoint(targetPos),
            //总的步长
            count = Math.round(me._getDistance(init_pos, target_pos) / step);
        //显示折线 syj201607191107
        this._map.addOverlay(new BMap.Polyline(pointsArr, {
            strokeColor: "#111",
            strokeWeight: 5,
            strokeOpacity: 0.5
        })); // 画线
        //如果小于1直接移动到下一点
        if (count < 1) {
            me._moveNext(++me.i);
            return;
        }
        me._intervalFlag = setInterval(function () {
            //两点之间当前帧数大于总帧数的时候，则说明已经完成移动
            if (currentCount >= count) {
                clearInterval(me._intervalFlag);
                //移动的点已经超过总的长度
                if (me.i > me._path.length) {
                    return;
                }
                //运行下一个点
                me._moveNext(++me.i);
            } else {
                currentCount++;
                var x = effect(init_pos.x, target_pos.x, currentCount, count),
                    y = effect(init_pos.y, target_pos.y, currentCount, count),
                    pos = me._projection.pointToLngLat(new BMap.Pixel(x, y));
                //设置marker
                if (currentCount == 1) {
                    var proPos = null;
                    if (me.i - 1 >= 0) {
                        proPos = me._path[me.i - 1];
                    }
                    if (me._opts.enableRotation == true) {
                        me.setRotation(proPos, initPos, targetPos);
                    }
                    if (me._opts.autoView) {
                        if (!me._map.getBounds().containsPoint(pos)) {
                            me._map.setCenter(pos);
                        }
                    }
                }
                //正在移动
                me._marker.setPosition(pos);
                //设置自定义overlay的位置
                me._setInfoWin(pos);
            }
        }, timer);
    };

    function lushuInstance(pointArr, carNo) {
        return new BMapLib.LuShu(map, pointArr, {
            defaultContent: carNo,//"从天安门到百度大厦"
            autoView: false,//是否开启自动视野调整，如果开启那么路书在运动过程中会根据视野自动调整
            icon: new BMap.Icon('http://developer.baidu.com/map/jsdemo/img/car.png', new BMap.Size(52, 26), {anchor: new BMap.Size(27, 13)}),
            speed: 100,
            enableRotation: true,//是否设置marker随着道路的走向进行旋转

            landmarkPois: [
                {lng: 116.306954, lat: 40.05718, html: '加油站', pauseTime: 2}
            ]

        });
    }


    function startLushu(index) {

//        lushuInstance(pointArr).start();
//        instanceArr[index].hideInfoWindow();
        instanceArr[index].start();


    }
</script>

</html>